const express = require('express');
const router = express.Router();
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');

// 用户登录
router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  
  try {
    // 查找用户
    const user = await User.findOne({ where: { username } });
    
    // 检查用户是否存在以及密码是否匹配
    // 注意：在实际应用中，密码应该被哈希存储，并使用 bcrypt 等库进行比较
    if (!user || user.password_hash !== password) {
      return res.status(401).json({ message: 'Invalid username or password' });
    }
    
    // 生成JWT token
    const token = jwt.sign(
      { userId: user.id, username: user.username, openid: user.openid },
      process.env.JWT_SECRET || 'default_secret',
      { expiresIn: '1h' }
    );
    
    res.json({ 
      message: 'Login successful',
      token,
      user: {
        id: user.id,
        username: user.username,
        nickname: user.nickname,
        avatar_url: user.avatar_url
      }
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 获取所有用户
router.get('/', async (req, res) => {
  try {
    const users = await User.findAll({
      attributes: ['id', 'username', 'nickname', 'avatar_url', 'openid', 'unionid', 'phone_number', 'created_at', 'updated_at']
    });
    res.json(users);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 根据ID获取用户
router.get('/:id', async (req, res) => {
  const { id } = req.params;
  try {
    const user = await User.findByPk(id, {
      attributes: ['id', 'username', 'nickname', 'avatar_url', 'openid', 'unionid', 'phone_number', 'created_at', 'updated_at']
    });
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    res.json(user);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 创建用户
router.post('/', async (req, res) => {
  const { username, password_hash, nickname, avatar_url, openid, unionid, phone_number } = req.body;
  try {
    const user = await User.create({ username, password_hash, nickname, avatar_url, openid, unionid, phone_number });
    res.status(201).json({ 
      id: user.id, 
      username: user.username, 
      nickname: user.nickname, 
      avatar_url: user.avatar_url, 
      openid: user.openid, 
      unionid: user.unionid,
      phone_number: user.phone_number
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 更新用户
router.put('/:id', async (req, res) => {
  const { id } = req.params;
  const { username, password_hash, nickname, avatar_url, openid, unionid, phone_number } = req.body;
  try {
    const [updatedRowsCount] = await User.update(
      { username, password_hash, nickname, avatar_url, openid, unionid, phone_number },
      { where: { id } }
    );
    if (updatedRowsCount === 0) {
      return res.status(404).json({ message: 'User not found' });
    }
    const updatedUser = await User.findByPk(id);
    res.json({ 
      id: updatedUser.id, 
      username: updatedUser.username, 
      nickname: updatedUser.nickname, 
      avatar_url: updatedUser.avatar_url, 
      openid: updatedUser.openid, 
      unionid: updatedUser.unionid,
      phone_number: updatedUser.phone_number
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 删除用户
router.delete('/:id', async (req, res) => {
  const { id } = req.params;
  try {
    const deletedRowsCount = await User.destroy({ where: { id } });
    if (deletedRowsCount === 0) {
      return res.status(404).json({ message: 'User not found' });
    }
    res.status(204).send();
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

module.exports = router;
